<template>
  <div class="room">
    <Card class="room-base" dis-hover :padding='0'>
      <p slot='title'>
          <span v-show='edit'>房间名:{{room_info.room_name == 'default'?'公区':room_info.room_name}}</span>
          <Input style='width:200px' v-model='room_info.room_name' v-show='!edit'></Input>
          <!-- <span style='font-size:14px;margin-left:14px' v-if="isWarningVisible">
              <span style='display:inline-block;width:12px;height:12px;background-color:#FF6A6A;border-radius:50%;'>
              </span>
              警告：长时间未开门
          </span> -->
      </p>
      <span slot='extra'>
          <Button class="margin-left-10" type='primary' v-show='edit==true'@click='edit=!edit' v-pmis="21">修改名称</Button>
          <Button class="margin-left-10" type='primary' v-show='edit==false' @click='ok'>保存名称</Button>
          <!--  <Button type='primary' @click="partition=true" v-show='home.home_type !=  HomeTypeEnum.DECENTRALIZED && room.room_type != RoomTypeEnum.PUBLIC && room.devices.length == 0 && room.parent_ids.length < 2'>
              分拆房间
          </Button> -->
      </span>
      <Row class="room-base-row">
        <!-- 租客详情，显示租客 -->
        <Col span="8" class="room-base-row-item" v-if="isShowRenterDetail">
            <Row type="flex" align="middle" class="room-base-row-item-line">
                <strong>租客详情</strong>
            </Row>
            <template v-if="roomHasLease">
                <template v-if="leaseHasTenant">
                    <Row class="room-base-row-item-line">
                        <span>姓名：</span>{{currentRoom.leases[0].tenant.name}}
                    </Row>
                    <Row class="room-base-row-item-line">
                        <span>电话：</span>{{currentRoom.leases[0].tenant.phone}}
                    </Row>
                    <Row class="room-base-row-item-line">
                        <span>租期：</span>{{currentRoom.leases[0].lease_range[0]|dateFrm}} - {{currentRoom.leases[0].lease_range[1]|dateFrm}}
                    </Row>
                </template>
                <div v-else style="margin:20px">
                    <strong style="font-size:15px">404-当前房间租约信息异常，请联系客服处理.</strong>
                    <!-- <i-button type="error" size="small" @click="handleDeleteLease">删除租约</i-button> -->
                </div>
            </template>
            <Row class="room-base-row-item-line">
                <Button
                    type="ghost"
                    class="yd-button margin-right-10"
                    v-pmis="30"
                    v-if="leaseHasTenant"
                    @click="showThrow">
                    退租
                </Button>
                <Button
                    type="ghost"
                    class="yd-button margin-right-10 margin-top-10"
                    v-pmis="30"
                    v-if="!roomHasLease"
                    @click="setCheckInVisible(true)">
                    入住
                </Button>
                <Button
                    type="ghost"
                    class="yd-button"
                    v-if="leaseHasTenant"
                    @click="toRenterDetail(currentRoom.leases[0].tenant.id,currentRoom.leases[0].tenant.name)">
                    更多
                </Button>
            </Row>
        </Col>
        <Col span="8" class="room-base-row-item" v-if="!isShowRenterDetail">
            <p class="special-line">{{renterTip}}</p>
        </Col>

        <!-- 分租 home.lease_type == 1 -->
        <template v-if="home && home.lease_type == 1">
          <!-- 分租公区---电表水表详情 -->
          <Col span='8' class='room-base-row-item' v-if="room && room.room_type == RoomTypeEnum.PUBLIC">
             
              <!-- 公区电表模式，读数，付费模式，剩余电量 -->
              <div v-if='hasElemeter'>
                <Row class='room-base-row-item-line'>
                  <strong>用电</strong>
                </Row>
                <Row style='padding:0px 0 5px 20px;color: #5B5B5B;'>
                  <Col span='24' style="margin-top:10px">
                    <strong>公区电表模式 : </strong>{{homeElemeterMode}}
                  </Col>

                  <Col span='24' style="margin-top:10px">
                    <strong>公区电表读数 : </strong>{{room_info.electric_read < 0 ? '0.00' : room_info.electric_read}}度
                  </Col>

                  <Col span='24' style="margin-top:10px">
                    <strong>付费模式 : </strong>{{ room_info.pay_type==2 ? '后付费':'预付费' }}
                  </Col>
                  <Col span='24' style="margin-top:10px" v-if="room_info.pay_type==1">
                    <strong>剩余电量：</strong>{{leftPower}}度
                  </Col>
                </Row>
              </div>

              <!-- 公区用水详情，热水，冷水表 -->
              <div v-if='hasWater'>
                <Row class='room-base-row-item-line'>
                  <strong>用水</strong>
                </Row>
                <Row style='padding:0px 0 5px 20px;color: #5B5B5B;'>
                  <Row :gutter='16' v-if="room_info.hot_water.indexOf('-') === -1">
                    <Col span='24'>
                      <strong>公区热水表读数:</strong>{{Number(room_info.hot_water).toFixed(2)}}
                    </Col>
                  </Row>
                  <Row :gutter='16' v-if="room_info.cold_water.indexOf('-') === -1">
                    <Col span='24'>
                      <strong>公区冷水表读数:</strong>{{Number(room_info.cold_water).toFixed(2)}}
                    </Col>
                  </Row>
                  <!-- <Row :gutter='16'>
                    <Col span='24'>
                      <strong>更新时间:</strong>
                    </Col>
                  </Row> -->
                </Row>
              </div>

              <div v-if='!hasWater && !hasElemeter'>
                <Row class='room-base-row-item-line'>
                  <strong> 当前的分租公区无电表，水表信息</strong>
                </Row>
              </div>
               
          </Col>

          <!-- 分租非公区---有设备，费用详情，用电，用水 -->
          <Col span="8" class="room-base-row-item" v-if="room && !!room.devices && room.room_type != RoomTypeEnum.PUBLIC">
            <Row type="flex" align="middle" class="room-base-row-item-line">
              <strong>费用详情</strong>
            </Row>

              <!-- 非公区用电 -->
              <div v-if="hasElemeter">
                <div class="room-base-row-item-line">
                  <strong>用电</strong>
                </div>
                <div style="padding:0px 0 5px 20px;color: #5B5B5B;">
                  <Row :gutter="16">
                    <i-col span="12" style="margin-bottom:6px;">
                      <strong>付费模式：</strong>{{ room_info.pay_type==2 ? '后付费':'预付费' }}
                    </i-col>
                    <i-col span="12" style="margin-bottom:6px;">
                      <strong>公区电费公摊：</strong>
                      <!-- 需要显示公摊系数 -->
                      <span>{{use_pool ? '已开启' : '已关闭'}}</span>
                      <span v-if="use_pool">
                        <!-- ({{homePoolSetting.pool_type | poolAreaType}}) -->
                        <span>{{pool_type === 1 ? '(均摊)' : '(按比例分摊:'}}</span>
                        <template v-if="pool_type === 1">
                          <!-- 均摊，是否需要显示有房间的房间总数-->
                        </template>
                        <template v-else>
                          <!--按比例分摊, 计算公摊系数，保留两位小数 -->
                          <span v-if="ratios[this.room.id] && ratios[this.room.id].ratio">
                            <!-- 计算公摊系数，保留两位小数 -->
                            {{((Number(ratios[this.room.id].ratio * 100 / sumRatio).toFixed(2))+ '%')}})
                          </span>
                          <span v-else>0%)</span>
                        </template>
                      </span>
                    </i-col>
                    <!-- 预付费模式增加剩余电量显示 -->                               
                    <i-col span="12" style="margin-bottom:6px;" v-if="room_info.pay_type === 1">
                      <strong>剩余电量：</strong>{{leftPower}}度
                    </i-col>
                  </Row>
                </div>
              </div>

              <!-- 非公区用水 -->
              <div v-if='hasWater'>
                <Row class='room-base-row-item-line'>
                  <strong>用水</strong>
                </Row>
                <Row style='padding:0px 0 5px 20px;color: #5B5B5B;'>
                  <Row :gutter='16'>
                    <Col span="12" style="margin-bottom:6px;" v-if="hasDevice(7)">
                      <strong>热水量：</strong>{{Number(room_info.hot_water).toFixed(2)}}
                    </Col>
                    <Col span="12" style="margin-bottom:6px;" v-if="hasDevice(6)">
                      <strong>冷水量：</strong>{{Number(room_info.cold_water).toFixed(2)}}
                    </Col>
                  </Row>
                </Row>
              </div>

              <div v-if='!hasWater && !hasElemeter'>
                <Row class='room-base-row-item-line'>
                  <strong> 当前的分租非公区无电表，水表信息</strong>
                </Row>
              </div>
          </Col>
        </template>

        <!-- 整租 home.lease_type != 1 -->
        <template v-if="home && home.lease_type != 1">
          
          <!-- 整租公区---电表水表详情 -->
          <Col span='8' class='room-base-row-item' v-if='room && room.room_type == RoomTypeEnum.PUBLIC'>
            <!-- 公区电表模式，读数，付费模式，剩余电量 -->
            <div v-if='hasElemeter'>
                <Row class='room-base-row-item-line'>
                    <strong>用电</strong>
                </Row>
                <Row style='padding:0px 0 5px 20px;color: #5B5B5B;'>
                    <Col span='24' style="margin-top:10px">
                        <strong>公区电表模式 : </strong>{{homeElemeterMode}}
                    </Col>

                    <Col span='24' style="margin-top:10px">
                        <strong>公区电表读数 : </strong>{{room_info.electric_read < 0 ? '0.00' : room_info.electric_read}}度
                    </Col>

                    <Col span='24' style="margin-top:10px">
                        <strong>付费模式 : </strong>{{ room_info.pay_type==2 ? '后付费':'预付费' }}
                    </Col>
                    <Col span='24' style="margin-top:10px" v-if="room_info.pay_type==1">
                        <strong>剩余电量：</strong>{{leftPower}}度
                    </Col>
                </Row>
            </div>

            <!-- 公区用水详情，热水，冷水表 -->
            <div v-if='hasWater'>
                <Row class='room-base-row-item-line'>
                    <strong>用水</strong>
                </Row>
                <Row style='padding:0px 0 5px 20px;color: #5B5B5B;'>
                    <Row :gutter='16' v-if="room_info.hot_water.indexOf('-') === -1">
                        <Col span='24'>
                            <strong>公区热水表读数:</strong>{{Number(room_info.hot_water).toFixed(2)}}
                        </Col>
                    </Row>
                    <Row :gutter='16' v-if="room_info.cold_water.indexOf('-') === -1">
                        <Col span='24'>
                            <strong>公区冷水表读数:</strong>{{Number(room_info.cold_water).toFixed(2)}}
                        </Col>
                    </Row>
                </Row>
            </div>

            <div v-if='!hasWater && !hasElemeter'>
              <Row class='room-base-row-item-line'>
                <strong> 当前的整租公区无电表，水表信息</strong>
              </Row>
            </div>

          </Col>

          <!-- 整租非公区---有设备，费用详情，用电，用水 -->
          <Col span="8" class="room-base-row-item" v-if="room && !!room.devices && room.room_type != RoomTypeEnum.PUBLIC">
            <Row type="flex" align="middle" class="room-base-row-item-line">
              <strong>费用详情</strong>
            </Row>

            <!-- 非公区用电 -->
            <div v-if="hasElemeter">
              <div class="room-base-row-item-line">
                <strong>用电</strong>
              </div>
              <div style="padding:0px 0 5px 20px;color: #5B5B5B;">
                <Row :gutter="16">
                  <i-col span="12" style="margin-bottom:6px;">
                    <strong>付费模式：</strong>{{ room_info.pay_type==2 ? '后付费':'预付费' }}
                  </i-col>
                  <i-col span="12" style="margin-bottom:6px;">
                    <strong>公区电费公摊：</strong>
                    <!-- 需要显示公摊系数 -->
                    <span>{{use_pool ? '已开启' : '已关闭'}}</span>
                    <span v-if="use_pool">
                      <!-- ({{homePoolSetting.pool_type | poolAreaType}}) -->
                      <span>{{pool_type === 1 ? '(均摊)' : '(按比例分摊:'}}</span>
                      <template v-if="pool_type === 1">
                        <!-- 均摊，是否需要显示有房间的房间总数-->
                      </template>
                      <template v-else>
                        <!--按比例分摊, 计算公摊系数，保留两位小数 -->
                        <span v-if="ratios[this.room.id] && ratios[this.room.id].ratio">
                            <!-- 计算公摊系数，保留两位小数 -->
                            {{((Number(ratios[this.room.id].ratio * 100 / sumRatio).toFixed(2))+ '%')}})
                        </span>
                        <span v-else>0%)</span>
                      </template>
                    </span>
                  </i-col>
                  <!-- 预付费模式添加剩余电量显示 -->                               
                  <i-col span="12" style="margin-bottom:6px;" v-if="room_info.pay_type == 1">
                    <strong>剩余电量：</strong>{{leftPower}}度
                  </i-col>
                </Row>
              </div>
            </div>

            <!-- 非公区用水 -->
            <div v-if='hasWater'>
              <Row class='room-base-row-item-line'>
                <strong>用水</strong>
              </Row>
              <Row style='padding:0px 0 5px 20px;color: #5B5B5B;'>
                <Row :gutter='16'>
                  <Col span="12" style="margin-bottom:6px;" v-if="hasDevice(7)">
                    <strong>热水量：</strong>{{Number(room_info.hot_water).toFixed(2)}}
                  </Col>
                  <Col span="12" style="margin-bottom:6px;" v-if="hasDevice(6)">
                    <strong>冷水量：</strong>{{Number(room_info.cold_water).toFixed(2)}}
                  </Col>
                </Row>
              </Row>
            </div>

            <div v-if='!hasWater && !hasElemeter'>
              <Row class='room-base-row-item-line'>
                <strong> 当前的整租非公区无电表，水表信息</strong>
              </Row>
            </div>
          </Col>

        </template>
        <!-- 房间常用操作 -->
        <Col span='8'>
            <Row type='flex' align='middle' class='room-base-row-item-line'>
                <strong>房间常用操作</strong>
            </Row>
            <Row class='room-base-row-action'>
                <Button type='ghost' class='yd-button room-base-row-action-button' v-pmis="27"
                @click="rechargeRoom" v-if='hasElemeter && room_info.pay_type == ElemeterPayMode.PREPAID'>电量充值</Button>

                <Button type='ghost' class='yd-button room-base-row-action-button'
                @click="restclean = true" v-if='hasElemeter && room_info.pay_type == ElemeterPayMode.PREPAID'>剩余电量清零</Button>

                <Button
                type='ghost'
                class='yd-button room-base-row-action-button'
                @click="eleOff = true"
                v-if='hasElemeter'
                v-pmis="26"
                :loading="isCheckingElemeterStatus">{{isCheckingElemeterStatus ? '电表操作中':'房间断电'}}</Button>

                <Button
                type='ghost'
                class='yd-button room-base-row-action-button'
                @click="eleOn = true"
                v-if='hasElemeter'
                v-pmis="26"
                :loading="isCheckingElemeterStatus">{{isCheckingElemeterStatus ? '电表操作中':'房间通电'}}</Button>

                <Button type='ghost' class='yd-button room-base-row-action-button'
                @click='openTab(109,2,room_info)' v-if='hasElemeter && room_info.pay_type == ElemeterPayMode.PREPAID' v-pmis="25">电表充值记录</Button>

                <Button type='ghost' class='yd-button room-base-row-action-button'
                @click="openTab(108,room_info.home_id,room_info)" v-if="shouldShowElemeterSetting" v-pmis="25">房间用电设置</Button>

                <Button type='ghost' class='yd-button room-base-row-action-button'
                @click="openTab(107,room_info.home_id,room_info)">房间安全配置</Button>

                <Button type='ghost' class='yd-button room-base-row-action-button'
                @click='openTab(110,0,room_info)' v-if='hasElemeter' v-pmis="25">查看用电记录</Button>

                <Button type='ghost' class='yd-button room-base-row-action-button'
                @click='openTab(111,1,room_info)' v-if='hasWater' v-pmis="25">查看用水记录</Button>

                <Button type='ghost' class='yd-button room-base-row-action-button' v-pmis="28"
                @click="getDynamicDasswords(device.id)" v-for='device in room_info.devices' v-if='device.device_type == DeviceTypeEnum.LOCK' :key='device.id'>获取临时密码</Button>

                <Button type='ghost' class='yd-button room-base-row-action-button' v-if="hasDevice(2)"
                @click='openLicensModal' v-pmis="25">授权管理</Button>
            </Row>
        </Col>
      </Row>

      <Row>
          <Modal v-model="eleOff" title="电表断电">
              <P style='text-align: center'>房间断电后，房间内所有电表将会跳闸断电。</P>
              <div slot="footer">
                  <Button type="text" @click='eleOff=false'>取消</Button>
                  <Button type="primary" @click='roomOff()' :loading="isSettingRoomElemeter">确定</Button>
              </div>
          </Modal>
          <Modal v-model="eleOn" title="电表通电">
              <P style='text-align: center'>房间通电后，房间内所有电表将会合闸通电。</P>
              <div slot="footer">
                  <Button type="text" @click='eleOn=false'>取消</Button>
                  <Button type="primary" @click='roomOn()' :loading="isSettingRoomElemeter">确定</Button>
              </div>
          </Modal>

          <getActPwd :visible="has_lease_dynamic" :lockDetail="{ id:lockId, roomId:room.id, roomName: room.room_name}" @on-close="has_lease_dynamic = false"></getActPwd>

          <Modal v-model="restclean" title="剩余电量清零">
              <div style='text-align: center'>
                  房间剩余电量:{{leftPower}}度,确定要清零吗？
              </div>
              <div slot="footer">
                  <Button type="text" @click='restclean=false'>取消</Button>
                  <Button type="primary" @click="clearLeftEle">清零</Button>
              </div>
          </Modal>

          <Modal v-model="recharge" title="充值电量">
              <div style='padding-left:130px;margin-bottom:15px'>
                  <span style='margin-right:10px;'>充值电量：</span>
                  <InputNumber :formatter="formatInput" v-model="amount" :min="1" :max="1000" @on-change="amountChange"/>&nbsp;&nbsp;度
              </div>
              <div style='padding-left:130px;margin-bottom:15px'>
                  <span style='margin-right:10px;'>充值金额：</span>
                  <!-- <span> {{money}} 元  </span> -->
                  <Input v-model="money" style="width:80px" @on-blur="moneyChange"/>
              </div>
              <div style='padding-left:130px;margin-bottom:15px'>
                  <span style='margin-right:10px;'>当前电价：</span>
                  <span> {{price ? price + ' 元/度' : '未知'}} </span>
              </div>
              <div slot="footer">
                  <Button type="text" @click='recharge=false'>取消</Button>
                  <Button type="primary" @click='elemeterCharge' :loading="chargeLoading">确定</Button>
              </div>
          </Modal>

          <Modal v-model="partition" title="分拆房间">
              <div style='text-align: center;margin-bottom:10px'>
                  <span>分拆房间数量:</span><Input style='width:200px' v-model='partitionNum'></Input>
              </div>
              <P style='text-align: center'>
              注：分拆成功后，请返回房间列表，针对分拆后的房间进行单个房间管理。</P>
              <div slot="footer">
                  <Button type="text" @click='partition=false'>取消</Button>
                  <Button type="primary" @click='partitionRoom(home.id)'>确定</Button>
              </div>
          </Modal>
      </Row>
    </Card>

      <Card class="room-device" dis-hover :padding="10">
          <p slot='title'>
              <span>设备详情</span>
          </p>
          <Row :gutter="20" class="margin-bottom-20" style="padding-top:10px">
              <i-col span="6">
                  <Select clearable v-model="deviceOptions.deviceType" placeholder="选择设备类型">
                      <Option
                          v-for="option in deviceOptions.options"
                          :key="option.id"
                          :value="option.id">
                          {{option.name}}
                      </Option>
                  </Select>
              </i-col>
              <!-- <i-col span="6">
                  <i-input placeholder="设备名称/SN" v-model="deviceOptions.keyword"></i-input>
              </i-col> -->
          </Row>
          <Table :columns="columns1" :data="tableData"></Table>
      </Card>

      <!-- 授权管理 -->
      <licenseRecord v-if="isLicenseRecordVisible" :visible="true" :room="room" :home="home" :roomName="room.room_name" @on-close="closeLicenseRecord"/>

      <renterOut
          :room="room_info"
          v-if="isThrowVisible"
          @cancelOut="cancelOut"
          @outSuccess="outSuccess">
      </renterOut>

      <!-- 入住 -->
      <renterCheckIn
          :home="home"
          :room="room_info"
          v-if="isCheckInModalVisible"
          @cancelCheckIn="setCheckInVisible(false)"
          @checkInSuccess="checkInSuccess"
      />
  </div>
</template>
<script>
import cloneDeep from 'lodash/cloneDeep'
import util from '@/libs/util'
import { http, api } from '@/libs/http'
import { DeviceTypeEnum, HomeTypeEnum, RoomTypeEnum, ElemeterPayMode } from '@/libs/const'
import { mapState, mapGetters } from 'vuex'
import dayjs from 'dayjs'
import renterOut from '@/views/renter/renterOut.vue'
import renterCheckIn from '@/views/renter/renterCheckIn.vue'
import licenseRecord from './licenseRecord.vue'
import getActPwd from './getActPwd.vue'
import { refreshRoom } from './room-list/util'
import bus from '@/libs/event-bus'

export default {
  name: 'room-detail',
  props: {
    room: Object,
    home: Object
  },
  created () {
    this.fetchHomeAccessControl()
    this.getPublicEleMode()
    this.getLockId()
    this.fetchHomePoolSetting() // 获取公摊配置的信息函数，用于费用详情展示
    bus.$on('refresh-room' + this.room.id, this.watchRoomChange)
    // this.checkEleIsPostPaid()
  },
  beforeDestroy () {
    bus.$off('refresh-room' + this.room.id, this.watchRoomChange)
    Object.values(this.timer).forEach(timer => {
      if (timer) clearInterval(timer)
    })
  },
  data () {
    return {
      use_pool: false, // 是否开启公摊
      pool_type: 0, // pool_type === 1 ? '均摊' : '按比例分摊'
      sumRatio: 0, // 公摊开启后，当前房源的所有房间的总份数，作为比率计算的分母
      deviceOptions: {
        // keyword: '',
        deviceType: '',
        options: DeviceTypeEnum.properties
      },
      timer: {},
      operating: false,
      chargeLoading: false,
      EleIsPostPaid: false, // 电表是否为后付费模式
      HomeTypeEnum: HomeTypeEnum,
      RoomTypeEnum: RoomTypeEnum,
      ElemeterPayMode: ElemeterPayMode,
      DeviceTypeEnum: DeviceTypeEnum,
      roomDetail: {},
      room_info: this.room,
      room_switch: '',
      elemeterMode: '',
      edit: true,
      eleOn: false,
      isThrowVisible: false,
      isCheckInModalVisible: false,
      eleOff: false,
      dynamic_passwords: false,
      passwords: '',
      invalid_time: '',
      has_lease_dynamic: false,
      clear: false,
      recharge: false,
      restclean: false,
      roomset: false,
      partition: false,
      partitionNum: '',
      amount: 0,
      money: 0,
      price: 0,
      visible: false,
      columns1: [
        {
          title: '名称',
          align: 'center',
          key: 'description',
          render: (h, params) => {
            return h('span', params.row.description || (DeviceTypeEnum.properties[params.row.device_type] && DeviceTypeEnum.properties[params.row.device_type].name))
          }
        },
        {
          title: '设备类型',
          key: 'device_type',
          align: 'center',
          render: (h, params) => {
            return h('span', params.row.device_type && DeviceTypeEnum.properties[params.row.device_type] ? DeviceTypeEnum.properties[params.row.device_type].name : '-')
          }
        },
        {
          title: '状态',
          key: 'online',
          align: 'center',
          render: (h, params) => {
            const { online, switch: switchStatus, device_type, low_power, longtime_no_open } = params.row
            // const hasLongtimeNocloseLock = [ 'lk-25', 'lk-17', 'lk-18', 'T3S', 'T2S', 'D2S' ].some(modelType => [ type, model ].includes(modelType.toLowerCase()) || [ type, model ].includes(modelType.toUpperCase()));
            const normal = []
            const error = []
            online === 1 ? normal.push('在线') : error.push('离线')
            if (device_type === 2) {
              if (low_power) error.push('低电')
              if (longtime_no_open) error.push('长时间未开门')
              // if (hasLongtimeNocloseLock) {
              //     !longtime_no_close ? normal.push('已锁') : error.push('未锁');
              // }
            }
            if (device_type === 3) {
              switchStatus === 1 ? normal.push('通电') : error.push('断电')
            }
            const style = error.length > 0 ? 'color:red' : ''
            return (
              <span style={style}>
                {[...normal, ...error].join(' / ')}
              </span>
            )
          }
        },
        {
          title: '备注',
          align: 'center',
          key: 'remark',
          render: (h, params) => {
            return h('span', params.row.remark || '-')
          }
        },
        {
          title: '操作',
          width: 250,
          align: 'center',
          render: (h, { row, index }) => {
            const commonStyle = {
              props: {
                type: 'ghost',
                size: 'small'
              },
              style: {
                marginRight: '5px'
              }
            }
            const { room_info, home, devicePermission, canUseM3Remote, operating } = this
            const { id, device_type, switch: switchStatus, deviceName, room_id, couter } = row
            const canTurnOnElemeter = device_type === 3 && switchStatus === 2
            const canTurnOffElemeter = device_type === 3 && (!switchStatus || switchStatus === 1)
            const shouldShowTimer = !!(couter && couter > 0)
            return (
              <div>
                <i-button
                  {...commonStyle}
                  onClick={() => { this.openTab(device_type, id, room_info, home, row) }}>
                                    查看
                </i-button>
                {
                  canTurnOnElemeter &&
                                    <i-button
                                      v-pmis={26}
                                      {...commonStyle}
                                      loading={this.isCheckingElemeterStatus}
                                      onClick={() => { this.elemeterOn(id) }}>
                                        电表通电
                                    </i-button>
                }
                {
                  canTurnOffElemeter &&
                                    <i-button
                                      v-pmis={26}
                                      {...commonStyle}
                                      loading={this.isCheckingElemeterStatus}
                                      onClick={() => { this.elemeterOff(id) }}>
                                        电表断电
                                    </i-button>
                }
                {
                  devicePermission &&
                                    <i-button
                                      v-pmis={23}
                                      {...commonStyle}
                                      onClick={() => { this.delDevice(device_type, id, index, deviceName, room_id) }}>
                                        解绑
                                    </i-button>
                }
                {
                  canUseM3Remote && device_type === 11 &&
                                    <i-button
                                      {...commonStyle}
                                      loading={operating}
                                      disabled={shouldShowTimer}
                                      onClick={() => { this.handleOpenFromRemote(room_id, id) }}>
                                        远程开门 { shouldShowTimer ? `(${couter}s)` : ''}
                                    </i-button>
                }
              </div>
            )
          }
        }
      ],
      data1: [],

      lockId: null,
      lastOpenTime: 0, // 最近开门时间
      isCheckingElemeterStatus: false, // 是否在查询通电状态
      isSettingRoomElemeter: false, // 是否正在进行房间电表操作
      isLicenseRecordVisible: false, // 授权管理modal显隐
      flag: false,
      accessControls: [],
      tableList: [] // 全部的设备列表
    }
  },
  methods: {
    // 获取房间公摊配置信息
    async fetchHomePoolSetting () {
      await http.request(this, api.home_pool_setting_info, [this.home.id], null, (res, err) => {
        if (!res || err) {
          return
        }
        const { use_pool, ratios, pool_type } = res // 解构出需要的数据
        // 下面的三个赋值，需要作非空判断
        if (use_pool) this.use_pool = use_pool
        if (ratios) this.ratios = ratios
        if (pool_type) this.pool_type = pool_type
        let sumRatioTemp = 0 // 用于累加房源所有有租客房间的比例份数
        Object.values(ratios).forEach(item => {
          // 后期需要考虑房间是否在有租客的情况下才进行计算
          if (item.ratio > 0) {
            sumRatioTemp += item.ratio
          }
        })
        this.sumRatio = sumRatioTemp // 结果赋值给当前页面的data属性
      })
    },
    handleOpenFromRemote (roomId, deviceId) {
      this.$Modal.confirm({
        loading: true,
        title: '提示',
        content: '确定进行远程开门?',
        onOk: () => {
          this.openFromRemote(roomId, deviceId)
        }
      })
    },
    setTimer (deviceId) {
      const deviceIndex = this.tableList.findIndex(d => d.id === deviceId)
      if (deviceIndex < 0) return
      this.$set(this.tableList[deviceIndex], 'couter', 10)

      this.timer[deviceId] = setInterval(() => {
        const tableList = cloneDeep(this.tableList)
        const currentValue = tableList[deviceIndex].couter
        if (currentValue > 0) {
          tableList[deviceIndex].couter = currentValue - 1
          this.tableList = tableList
        } else {
          if (this.timer[deviceId]) {
            clearInterval(this.timer[deviceId])
            this.timer[deviceId] = null
          }
        }
      }, 1000)
    },
    async openFromRemote (roomId, deviceId) {
      try {
        this.operating = true
        const res = await http.req(api.m3_open, [roomId, deviceId], null)
        if (res) {
          this.$Message.success('远程开门成功')
        }
      } catch (err) {
        console.log(err)
      } finally {
        this.$Modal.remove()
        this.operating = false
        this.setTimer(deviceId)
      }
    },
    // handleDeleteLease() {
    //     this.$Modal.confirm({
    //         loading: true,
    //         title: '提示',
    //         content: '确认删除租约, 删除后可正常入住?',
    //         onOk: () => {
    //             this.deleteLease();
    //         }
    //     });
    // },
    // async deleteLease() {
    //     const { room } = this;
    //     const leaseId = room.leases[0].id;
    //     try {
    //         const res = await http.req(api.tenant_leases_del, [leaseId]);
    //         if (res) {
    //             this.$Message.success('退租成功');
    //             this.updateRoomAndHome();
    //         }
    //     } catch (err) {
    //         console.log(err);
    //     } finally {
    //         this.$Modal.remove();
    //     }
    // },
    watchRoomChange () {
      this.getRoomDetail()
    },
    /** 如果是公区, 查找房源下的全部门禁, 用于楼栋门禁显示在公区下的需求 */
    async fetchHomeAccessControl () {
      const { room_type, home_id, devices } = this.room
      this.accessControls = []
      if (room_type === 2) {
        const accessControls = await http.req(api.face_access_of_home, [ home_id ], null, true)
        const deviceIds = devices.map(d => d.id)
        accessControls.forEach(d => { return (d.isBuildingDevice = true) })
        this.accessControls = accessControls
          .filter(ac => !deviceIds.includes(ac.id))
          .map(d => ({
            isBuildingDevice: true,
            ...d
          }))
      }
    },
    hasDevice (type) {
      return this.room && this.room.devices.some(device => device.device_type === type)
    },
    formatInput (newVal) {
      if (newVal < 0) {
        this.amount = 1
        this.amountChange()
      }

      return this.amount
    },
    getPublicEleMode () {
      if (this.room.room_type === RoomTypeEnum.PUBLIC) {
        http.request(this, api.home_pool_setting_info, [this.home.id], null, (res, err) => {
          if (!res || err) {
            return
          }
          this.elemeterMode = res.pool_area_type
        })
      }
    },
    getDynamicDasswords (deviceId) {
      util.log(this.room)
      util.log(this.home)
      this.has_lease_dynamic = true
    },
    // 轮询电表基本信息
    get_elemeter_switch_state (roomId, id, type) {
      this.isCheckingElemeterStatus = true
      let timeoutStart = new Date().getTime()
      let timer = setInterval(() => {
        let diffTime = new Date().getTime() - timeoutStart
        if (diffTime > 180000) {
          clearInterval(timer)
          this.$Message.warning(`电表远程${type === 'close' ? '断电' : '通电'}超时`)
          this.isCheckingElemeterStatus = false
        }
        http.request(this, api.elemeter_info, [roomId, id], null, (res, err) => {
          if (!res || err) {
            return
          }

          if (res.switch_stage === 1) {
            console.log('电表操作轮询中', diffTime / 1000)
          } else if (res.switch_stage === 2) {
            clearInterval(timer)
            this.isCheckingElemeterStatus = false
            this.$Message.error(`电表远程${type === 'close' ? '断电' : '通电'}失败`)
          } else if (res.switch_stage === 3) {
            clearInterval(timer)
            this.isCheckingElemeterStatus = false
            if (type === 'close') {
              this.$Message.success('设置远程断电成功')
            }
            if (type === 'open') {
              this.$Message.success('设置远程通电成功')
            }
            this.getRoomDetail()
          } else {
            clearInterval(timer)
            this.isCheckingElemeterStatus = false
            console.log('get elemeter info error:' + res.ErrMsg + '(' + res.ErrNo + ')')
          }
        })
      }, 3000)
    },
    // 通电轮询房间基本信息
    get_room_switch_state_on (roomId) {
      this.isCheckingElemeterStatus = true
      let timeoutStart = new Date().getTime()
      let timer = setInterval(() => {
        let diffTime = new Date().getTime() - timeoutStart
        if (diffTime > 180000) {
          clearInterval(timer)
          this.isCheckingElemeterStatus = false
          this.$Message.info('房间通电操作超时，请稍后重试')
          return
        }

        http.request(this, api.room_info, [roomId], null, (res, err) => {
          this.room_info = res
          let allElemeterOnDone = true
          if (res.devices.length !== 0) {
            for (let i = 0; i < res.devices.length; i++) {
              if (res.devices[i].device_type === 3 && res.devices[i].switch === 2) {
                this.allElemeterOnDone = false
                break
              }
            }
          }
          if (allElemeterOnDone) {
            // 所有的都成功
            clearInterval(timer)
            this.$Message.success('房间通电操作成功')
            this.isCheckingElemeterStatus = false
          }
        })
      }, 3000)
    },
    // 断电轮询房间基本信息
    get_room_switch_state_off (roomId) {
      this.isCheckingElemeterStatus = true
      let timeoutStart = new Date().getTime()
      let timer = setInterval(() => {
        let diffTime = new Date().getTime() - timeoutStart
        if (diffTime > 180000) {
          clearInterval(timer)
          this.isCheckingElemeterStatus = false
          this.$Message.info('房间断电操作超时，请稍后重试')
          return
        }
        http.request(this, api.room_info, [roomId], null, (res, err) => {
          this.room_info = res
          let allElemeterOffDone = true
          if (res.devices.length !== 0) {
            for (let i = 0; i < res.devices.length; i++) {
              if (res.devices[i].device_type === 3 && res.devices[i].switch === 1) {
                allElemeterOffDone = false
                break
              }
            }
          }

          if (allElemeterOffDone) {
            clearInterval(timer)
            this.isCheckingElemeterStatus = false
            this.$Message.success('房间断电操作成功')
          }
        })
      }, 3000)
    },
    getRoomDetail () {
      http.request(this, api.room_info, [this.room_info.id], null, (res, err) => {
        if (!res || err) {
          return
        }
        console.log('查看rooid', res)
        this.room_info = res
      })
    },
    // params.row.device_type, params.row.id, this.room_info, this.home
    openTab (type, id, roomInfo, homeInfo, device) {
      if ([10, 11].includes(type)) {
        this.$emit('openType', (device && device.room_id) || this.room.id, 'device', id, roomInfo.room_name, roomInfo, homeInfo, device)
      } else if (type === 107) {
        this.$emit('openType', roomInfo.id || this.room.id, type, id, roomInfo.room_name, roomInfo, homeInfo)
      } else {
        this.$emit('openType', (device && device.room_id) || this.room.id, type, id, roomInfo.room_name, roomInfo, homeInfo)
      }
    },

    // 电量充值
    rechargeRoom () {
      let permission = this.$store.state.app.permission
      if (permission && !permission['opt_room_charge_elemeter']) {
        this.$Message.error('商户权限受限，请联系对接的商务或销售')
        return
      }

      this.recharge = true
      http.request(this, api.room_elemeter_setting, [this.room_info.id], null, (res, err) => {
        if (!res || err) {
          return
        }
        let { ele_price } = res
        this.price = ele_price.value ? ele_price.value : ele_price.parent_value ? ele_price.parent_value : undefined
        this.amount = 1
        this.money = (Number(this.price) * this.amount).toFixed(2)
        // if (res.room_setting.ele_price) {
        //     this.price = res.room_setting.ele_price
        // } else {
        //     this.price = res.parent_setting.ele_price.value ? res.parent_setting.ele_price.value : 0
        // }
      })
    },
    closeSendPwd () {
      this.visible = false
    },
    roomOff () {
      this.isSettingRoomElemeter = true
      http.request(this, api.elemeters_off, [this.room_info.id], null, (res, err) => {
        this.isSettingRoomElemeter = false
        if (!res || err) {
          return
        }
        this.$Message.success('已发送断电请求，请稍后')
        this.get_room_switch_state_off(this.room_info.id)
        this.eleOff = false
      })
    },
    roomOn () {
      this.isSettingRoomElemeter = true
      http.request(this, api.elemeters_on, [this.room_info.id], null, (res, err) => {
        this.isSettingRoomElemeter = false
        if (!res || err) {
          return
        }
        this.$Message.success('已发送通电请求，请稍后')
        this.get_room_switch_state_on(this.room_info.id)
        this.eleOn = false
      })
    },
    elemeterOff (id) {
      this.$Modal.confirm({
        width: '300px',
        content: '断电后该电表将会跳闸断电。',
        onOk: () => {
          let room = this.room_info
          this.isSettingRoomElemeter = true
          http.request(this, api.elemeter_close, [room.id, id], null, (res, err) => {
            this.isSettingRoomElemeter = false
            if (!res || err) {
              return
            }
            this.$Message.success('已发送电表断电请求，请稍后')
            this.get_elemeter_switch_state(this.room_info.id, id, 'close')
          })
        }
      })
    },
    elemeterOn (id) {
      this.$Modal.confirm({
        width: '300px',
        content: '通电后该电表将会合闸通电。',
        onOk: () => {
          let room = this.room_info
          this.isSettingRoomElemeter = true
          http.request(this, api.elemeter_open, [room.id, id], null, (res, err) => {
            this.isSettingRoomElemeter = false
            if (!res || err) {
              return
            }
            this.$Message.success('已发送电表通电请求，请稍后')
            this.get_elemeter_switch_state(this.room_info.id, id, 'open')
          })
        }
      })
    },
    async clearLeftEle () {
      // 剩余电量清零
      const roomId = this.room_info.id
      const res = await http.req(api.room_elemeter_reset, [roomId], null)
      if (res) {
        this.$Message.success('剩余电量清零成功')
        this.restclean = false
        this.getRoomDetail()
      }
    },
    elemeterCharge: util.throttle(function () {
      this.chargeLoading = true

      let room = this.room_info

      const amount = this.amount

      if (isNaN(amount) || Number(amount) < 0) {
        this.$Message.success('充值电量必须为正整数!')
        return
      }

      this.isSettingRoomElemeter = true
      http.request(this, api.elemeter_charge, [room.id], { amount }, (res, err) => {
        if (res) {
          this.recharge = false
          this.$Message.success('充值成功')
          // 刷新房源房间列表
          refreshRoom(this.room_info.home_id, this.room_info.id)
        }
        if (this.room_info.force_open) {
          this.$Notice.warning({
            title: '提示',
            duration: 8,
            desc: '当前房间强制断电，请手动通电'
          })
        }
        setTimeout(() => {
          this.isSettingRoomElemeter = false
          this.chargeLoading = false
        }, 500)
      })
    }),

    ok () {
      this.edit = !this.edit
      let room = this.room_info
      http.request(this, api.room_update, [room.id], { room_name: room.room_name }, (res, err) => {
        if (!res || err) {
          return
        }
        this.$Message.success('修改名称成功')

        // 刷新房源房间列表
        refreshRoom(this.room_info.home_id, this.room_info.id)
      })
    },
    showThrow () {
      this.isThrowVisible = true
    },
    setCheckInVisible (value) {
      this.isCheckInModalVisible = value
    },
    delDevice (type, id, index, deviceName, roomId) {
      const deviceTypeName = DeviceTypeEnum.properties[type] && DeviceTypeEnum.properties[type].name
      const delApiList = {
        0: '',
        1: 'gateway_del',
        2: 'lock_del',
        3: 'elemeter_del',
        4: 'elecollector_del',
        5: 'watergateway_del',
        6: 'watermeter_del',
        7: 'watermeter_del',
        8: 'elecollector_del',
        10: 'face_accesss_del',
        11: 'm3_accesss_del'
      }

      let content = type !== '10' ? `确定<strong style="color:#f00"> 解绑 </strong>
                ${util.escapeHtml(deviceTypeName)} <strong style="color:#05bac5">
                ${util.escapeHtml(deviceName)}</strong>?` : `确定<strong style="color:#f00"> 解绑 </strong>
                ${util.escapeHtml(deviceTypeName)} <strong style="color:#05bac5">
                ${util.escapeHtml(deviceName)}</strong>? 解绑门禁会清空系统记录的授权记录。`

      this.$Modal.confirm({
        width: '300px',
        content: content,
        onOk: () => {
          const finalApi = api[delApiList[type]]
          http.request(this, finalApi, [roomId, id], null, (res, err) => {
            if (!res || err) {
              return
            }
            this.$Message.success(`${deviceTypeName}解绑成功`)
            this.devices.splice(index, 1)
            this.updateRoomAndHome()
            this.fetchHomeAccessControl()
          })
        }
      })
    },
    updateRoomAndHome () {
      // 刷新房源房间列表
      refreshRoom(this.room_info.home_id, this.room_info.id)
      this.$emit('on-load-device') // 更新device
    },
    cancelOut () {
      this.isThrowVisible = false
    },
    outSuccess () {
      this.isThrowVisible = false

      // 刷新房源房间列表
      this.updateRoomAndHome()
    },
    checkInSuccess () {
      this.isCheckInModalVisible = false

      // 刷新房源房间列表
      this.updateRoomAndHome()
    },
    partitionRoom (id) {
      let rooms = []
      let partitionNum = Number(this.partitionNum)
      let arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
      for (let i = 0, len = partitionNum; i < len; i++) {
        rooms.push({ name: this.room.room_name + '-' + arr[i] })
      }
      http.request(this, api.room_create, [id], { rooms: rooms, parent_id: this.room.id }, (res, err) => {
        this.partition = false
        if (err || !res) {
          return
        }
        this.$Message.success('分拆成功')
        // this.$emit('on-refresh')
        this.$store.commit('refresh_room', Math.random())
      })
    },
    showAddPwdModal () {
      this.visible = true
    },
    toRenterDetail (renter_id, renter_name) {
      this.$router.push({
        path: '/renter/index',
        query: {
          renter_id,
          renter_name
        }
      })
    },
    getLockId () {
      for (let i of this.devices) {
        if (i.device_type === DeviceTypeEnum.LOCK) {
          this.lockId = i.id
        }
      }
    },
    // getLastOpenTime(lockId) {
    //     // 开门记录取最近一次开门时间
    //     let params = {
    //         start_time: Date.now() - 72 * 60 * 60 * 1000,
    //         end_time: Date.now()
    //     }
    //     http.request(this, api.lock_open_log, [this.room_info.id, lockId], params, (res, err) => {
    //         if (res && res.list[0]) {
    //             this.lastOpenTime = res.list[0].time
    //         }
    //     })
    // },
    openLicensModal () {
      this.isLicenseRecordVisible = true
    },
    closeLicenseRecord () {
      this.isLicenseRecordVisible = false
    },
    moneyChange () {
      // console.log(typeof this.money, typeof this.price);
      // console.log(Number(this.money), Number(this.price));
      if (Number(this.money) < 0) {
        this.money = 1
      }
      this.amount = Number(this.money) / Number(this.price)
    },
    amountChange () {
      this.money = Math.round(this.price * this.amount * Math.pow(10, 2)) / Math.pow(10, 2)
    },
    setTableList (result) {
      this.tableList = result
    }
  },
  filters: {
    dateFrm: function (el) {
      if (el === -1 || !el) {
        return ' - '
      }
      return dayjs(el).format('YYYY-MM-DD HH:mm:ss')
    },
    leaseStatus (lease) {
      if (!lease) {
        return '暂无'
      }
      const start = new Date(lease.lease_range[0])
      const end = new Date(lease.lease_range[1])
      const frozenStatus = lease.op_status
      const now = Date.now()
      if (now < start) {
        return '未生效'
      }
      if (now > end) {
        return '已过期'
      }
      return frozenStatus === 1 ? '生效中' : '已冻结'
    }
  },
  computed: {
    ...mapState({
      devicePermission: state => state.user.devicePermission
    }),

    ...mapGetters(['canUseM3Remote']),
    /** 当前条件下的设备列表 */
    tableData () {
      const { tableList, deviceOptions: { deviceType } } = this
      if (!tableList || tableList.length === 0) return []
      if (!deviceType) return tableList
      const shouldShowDevice = Number(deviceType)
      // const shouldShowDevice = deviceType.split(',');
      // if (!keyword && !deviceType) return tableList;
      return tableList.filter(({ device_type, sn, deviceName }) => {
        return device_type === shouldShowDevice
        // const correctDeviceType = shouldShowDevice.length ? shouldShowDevice.includes(device_type) : true;
        // const correctName = keyword ? (deviceName.includes(keyword) || sn.includes(keyword)) : true;
        // return correctDeviceType && correctName;
      })
    },
    currentRoom () {
      const { room, room_info } = this
      const current = room || room_info
      if (current.leases) return current
      return { ...current, leases: [current.lease] }
    },
    roomHasLease () {
      const { currentRoom } = this
      if (!currentRoom) return false
      return currentRoom.leases && currentRoom.leases[0]
    },

    leaseHasTenant () {
      const { currentRoom, roomHasLease } = this
      return roomHasLease && !!currentRoom.leases[0].tenant
    },
    /**
        * 是否显示租客详情
        */
    isShowRenterDetail () {
      if (this.home && this.room) {
        const { lease_type } = this.home
        const { room_type } = this.room
        if (lease_type === 1) return room_type === RoomTypeEnum.COMMON
        if (lease_type === 2) return room_type === RoomTypeEnum.PUBLIC
        return false
      } else {
        return false
      }
    },
    // 分租公区不展示用电配置
    shouldShowElemeterSetting () {
      const { room, home } = this
      if (!room && !home) return false
      return !(home.lease_type === 1 && room.room_type === 2)
    },

    renterTip () {
      return (this.room && this.room.room_type === this.RoomTypeEnum.PUBLIC)
        ? '分租房源，公区不支持预付费及租客入住'
        : '整租房源，房间不支持办理租客入住，请在公区登记入住或增加同租人'
    },

    devices () {
      const { properties } = DeviceTypeEnum
      const { room_info: { devices }, accessControls } = this
      const result = [ ...devices, ...accessControls ]
      result.forEach(device => {
        device.couter = 0
        device.deviceName = device.description || (properties[device.device_type] && properties[device.device_type].name) || ''
      })
      this.setTableList(result) // 缓存全部设备数据
      return devices
    },
    hasElemeter () {
      for (let i of this.devices) {
        if (i.device_type === DeviceTypeEnum.ELEMETER) {
          return true
        }
      }
      return false
    },
    hasWater () {
      for (let i of this.devices) {
        if (i.device_type === DeviceTypeEnum.WATERMETER_COLD || i.device_type === DeviceTypeEnum.WATERMETER_HOT) {
          return true
        }
      }
      return false
    },
    leftPower () {
      let room = this.room_info
      if (room) {
        return util.getLeftElectric(room)
      }
      return '0.00'
    },
    totalElectric () {
      let room = this.room_info
      if (room) {
        return (Number(room.electric_read) + Number(room.pool_read)).toFixed(2)
      }
      return '0.00'
    },
    homeElemeterMode () {
      let elemeterMode = this.elemeterMode
      if (elemeterMode) {
        switch (elemeterMode) {
          case 1:
            return '总电表模式'
          case 2:
            return '独立电表模式'
        }
      }
      return '未设置公摊电表模式'
    }
    // isWarningVisible() {
    //     /**
    //      * 是否显示未开门警告
    //      * 1、有门锁；
    //      * 2、符合这个预警的条件： a、有租客； b、离最后一次使用密码开门超过72小时；
    //      */
    //     return this.lockId && this.room_info.lease && this.room_info.lease.id && Date.now() - this.lastOpenTime > 72 * 60 * 60 * 1000
    // }
  },
  components: {
    renterOut,
    renterCheckIn,
    licenseRecord,
    getActPwd
  }
}
</script>
<style lang='less'>
@import '../../styles/common.less';
.show {
    display: inline-block !important;
}
.room {
    font-size: 14px;
    &-base {
        background-color: #fff !important;
        &-row {
            min-height: 255px;
            &-item {
                border-right: 1px dashed #ccc;
                height: 255px;
                &-line {
                    padding: 15px 0 5px 20px;
                    font-size: 14px;
                    color: #000000;
                }
            }
            &-action {
                padding: 9px 0 5px 20px;
                max-width: 400px;
                &-button {
                    width: 120px;
                    float: left;
                    margin-right: 20px;
                    margin-bottom: 15px;
                }
            }
        }
    }
    &-device {
        background-color: #fff;
    }
}
.special-line {
    text-align: center;
    line-height: 255px;
    font-size: 14px;
}
</style>